package com.blockchainenergy.common;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.Arrays;
import java.util.Iterator;

public class ExcelReader {
    /**
     * 将Excel文件转成字符串数组。支持xls、xlsx
     *
     * @param in Excel文件输入流
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static int[][] copyData(InputStream in) throws IOException, InvalidFormatException {
        Workbook wb = WorkbookFactory.create(in);
        Sheet sheet = wb.getSheetAt(0);
        int rowNumber = sheet.getPhysicalNumberOfRows();
        Iterator<Row> rowIterator = sheet.rowIterator();
        Row titleRow = rowIterator.next();
        int columnNumber = titleRow.getLastCellNum();
        rowIterator = sheet.rowIterator();// 刷新迭代器，目的是从第0排开始算
        int[][] table = new int[rowNumber][columnNumber];
        for (int i = 0; i < rowNumber && rowIterator.hasNext(); i++) {
            Row row = rowIterator.next();
            for (int j = 0; j < columnNumber; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    cell.setCellType(CellType.NUMERIC);// 设置cell的字符类型
                    table[i][j] = (int) Math.round(cell.getNumericCellValue());
                } else {
                    table[i][j] = 0;
                }
            }
        }
        return table;
    }

    /**
     * 将Excel文件转成字符串数组。支持xls、xlsx
     *
     * @param bytes Excel文件字节数组
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static int[][] copyData(byte[] bytes) throws IOException, InvalidFormatException {
        return copyData(new ByteArrayInputStream(bytes));
    }

    /**
     * 将Excel文件转成字符串数组。支持xls、xlsx
     *
     * @param file Excel文件
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static int[][] copyData(File file) throws IOException, InvalidFormatException {
        return copyData(new FileInputStream(file));
    }

    public static int[][] copyData(String fileName) throws IOException, InvalidFormatException {
        return copyData(new FileInputStream(fileName));
    }
}
